from django.core.cache import cache

from goods.models import GoodsChannelGroup, SKU


def get_categories():

    data = cache.get('channel_data')
    if data:
        return data

    data = {}
    channel_groups = GoodsChannelGroup.objects.all()

    for group in channel_groups:
        group_data = {'channels': [], 'sub_cats': []}

        data[group.id] = group_data

        channels = group.goodschannel_set.all()
        for channel in channels:
            channel_data = {'id': channel.id, 'name': channel.category.name, 'url': channel.url}

            group_data['channels'].append(channel_data)

            cat1 = channel.category
            cat2_all = cat1.subs.all()
            for cat2 in cat2_all:
                cat2_data = {'id': cat2.id, 'name': cat2.name, 'sub_cats': []}
                group_data['sub_cats'].append(cat2_data)

                cat3_all = cat2.subs.all()
                for cat3 in cat3_all:
                    cat3_data = {'id': cat3.id, 'name': cat3.name}
                    cat2_data['sub_cats'].append(cat3_data)

    cache.set('channel_data', data, 3600 * 24 * 14)
    return data


def get_hots(category_id):
    """获取热销商品"""
    skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[0: 2]

    hot_skus = []
    for sku in skus:
        sku_data = {
            'id': sku.id,
            'img_url': sku.default_image_url.url,
            'name': sku.name,
            'price': sku.price
        }
        hot_skus.append(sku_data)

    return hot_skus